package com.bo.sina.weibo.image;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.bo.exception.AppException;
import com.bo.sina.send.WeiboResponse;
import com.bo.sina.weibo.access.AccessInfo;
import com.bo.sina.weibo.login.Login;

public class WeiboImage {

	/**
     * 上传方法
     * 返回上传完毕的文件名
     * *
	 * @throws IOException 
	 * @throws AppException 
     */
    public String upload(AccessInfo accessInfo,byte[] pic) throws IOException, AppException
    {
//                     http://picupload.service.weibo.com/interface/pic_upload.php?
//        cb=http%3A%2F%2Fweibo.com%2Faj%2Fstatic%2Fupimgback.html%3F_wv%3D5%26callback%3DSTK_ijax_13762837501178
//        &url=weibo.com%2Fu%2F3551120592&markpos=1&logo=1&nick=%40%E5%A8%B1%E8%AE%B0%E5%B0%8F%E6%8B%8D%E5%AE%A2
//            &marks=1&app=miniblog&s=rdxt

    	String urlstr="http://picupload.service.weibo.com/interface/pic_upload.php?app=miniblog&data=1" +
		"&url=weibo.com/u/" +accessInfo.getUid()+
		"&markpos=1&logo=1" +
		"&nick=" +java.net.URLEncoder.encode("@"+accessInfo.getNick(), "utf-8")+
		"&marks=1&mime=image/jpeg" 
//		+"&ct=0.367223285138607"
		;
    	
    	
		Map<String,String> requestMap=new HashMap<String,String>();

		
		requestMap.put("Host","picupload.service.weibo.com");
		requestMap.put("Connection","keep-alive");
//		requestMap.put("Content-Length","1188");
		requestMap.put("Origin","http://js.t.sinajs.cn");
		requestMap.put("User-Agent","Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
		requestMap.put("content-type","application/octet-stream");
		requestMap.put("Accept","*/*");
		requestMap.put("Referer","http://js.t.sinajs.cn/t5/home/static/swf/MultiFilesUpload.swf?version=1966e44616afe7cd");
		requestMap.put("Accept-Encoding","gzip,deflate,sdch");
		requestMap.put("Accept-Language","zh-CN,zh;q=0.8");
		requestMap.put("Accept-Charset","GBK,utf-8;q=0.7,*;q=0.3");
//		requestMap.put("Cookie","SINAGLOBAL=764228138141.3341.1372691224374; myuid=3316042027; un=bobo0218bo@126.com; wvr=5; SUE=es%3D0f57bae0161c3be65f64ec1ebe60f1e4%26ev%3Dv1%26es2%3Dc4a018617b30df46be9261e2d32996a1%26rs0%3DwHY7LUUsTgnY0Re58Mb3uxp6Ta%252BNwP39HPr6%252BK0H0Ze9NmflT%252BNbAkQGubtymBpoKKyasaqx8Iv%252B148ez3mSLSPIrndqJ2vWVzm%252Bt9FdWC%252FcTrT%252FFipAEqRDiB6oVA7EIMipKkAhmK5YgCPmUBcJLLHdJlr8bilgSk5TUTqDU3Q%253D%26rv%3D0; SUP=cv%3D1%26bt%3D1373120258%26et%3D1373206658%26d%3Dc909%26i%3D990d%26us%3D1%26vf%3D0%26vt%3D0%26ac%3D2%26st%3D0%26uid%3D1899962304%26name%3Dbobo0218bo%2540126.com%26nick%3Dbobo0218bo%26fmp%3D%26lcp%3D2013-01-26%252014%253A06%253A11; SUS=SID-1899962304-1373120258-JA-cy64u-42fe302ab2ea367d809ff94032f7a21c; ALF=1375694228; SSOLoginState=1373120258; _s_tentry=weibo.com; Apache=3948187199421.227.1373120298155; ULV=1373120298200:7:7:7:3948187199421.227.1373120298155:1373102178800; UOR=,,login.sina.com.cn; ULOGIN_IMG=13731272033123");
		
		requestMap.put("Cookie",accessInfo.getSession());

		HttpURLConnection uc=null;
        try
        {

            URL url = new URL(urlstr);
            uc = (HttpURLConnection) url.openConnection();
//            uc.setRequestProperty("Connection", "Keep-Alive");
            uc.setDoOutput(true);
            uc.setUseCaches(true);
            
            
            for(Entry<String,String> entry:requestMap.entrySet()){
           	 uc.setRequestProperty(entry.getKey(),entry.getValue());
            }
        
            //读取文件流
            OutputStream out = uc.getOutputStream();
            //写入图片流
            out.write(pic);
            out.flush();
            out.close();
            
            //读取响应数据
            int code = uc.getResponseCode();
            String sCurrentLine = "";
            //存放响应结果
            String sTotalString = "";
            if (code == 200)
            {
                java.io.InputStream is = uc.getInputStream();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is));
                while ((sCurrentLine = reader.readLine()) != null)
                    if (sCurrentLine.length() > 0)
                        sTotalString = sTotalString + sCurrentLine.trim();
            }
            else
            {
                java.io.InputStream is = uc.getInputStream();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is));
                while ((sCurrentLine = reader.readLine()) != null)
                    if (sCurrentLine.length() > 0)
                        sTotalString = sTotalString + sCurrentLine.trim();
                
            	throw  new AppException(String.valueOf(code),sTotalString.toString());
            }
//            System.out.println(sTotalString);
            String temp="\"pid\":\"";
            int pid=sTotalString.indexOf(temp);
            if(sTotalString.indexOf("code\":\"A00006")!=-1 && pid!=-1){
            	
            	String str=sTotalString.substring(pid+temp.length(), sTotalString.length());
            	String spid=str.substring(0, str.indexOf("\""));
            	return spid;
            }else{
            	throw  new AppException("A20001","发布图片失败："+sTotalString.toString());
            }
            
        }
        finally{   
            uc.disconnect();   
        }    
        }
    
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		byte[] pic=HttpImage.getUrlImg("http://r3.ykimg.com/050B000052085CE66714C04A030760A5");
//		AccessInfo accessinfo=new AccessInfo("1899962304", "淘宝抢特价", "bobo0218bo@126.com", "qwertyuiop[]\\");
		AccessInfo accessinfo=new AccessInfo("3558552770", "哥爱哈根达斯", "dsfer3@qq.com", "uy643efg");
//		//session为null 必须先登录微博
		if(accessinfo.getSession()==null){
			Login login=new Login();
			WeiboResponse loginresp=login.loginWeibo(accessinfo);
			accessinfo.setSession(loginresp.getSession());
		}
		
		WeiboImage image=new WeiboImage();
		System.out.println(image.upload(accessinfo,pic)); ;
	}

}
